const router = require('koa-router')()

// 生成雪花ID的方法
const createSnow = function (ctx) {
    let snowFlake = ctx.snowFlake;
    let snowId = snowFlake.createSnow(10);
    return snowId;
}
//对数组进行分组的方法
function forGroup(array, subGroupLength) {
    let index = 0;
    let newArray = [];
    while (index < array.length) {
        newArray.push(array.slice(index, index += subGroupLength));
    }
    return newArray;
}


router.prefix('/submitjob')
// router.get('/getEchartsData', async(ctx, next) => {//获取饼状图数据
//     console.log("getEchartsData");
//     let sql = "select * from course";
//     let res = await ctx.db.EXCUTE(sql,[])
//     // console.log(res);

//     ctx.body = {code: 200, msg: "查询成功", res}
// })
router.post('/getCourse', async (ctx, next) => {
    // console.log("getCourse");
    let id = ctx.request.body.id;
    let sql = 'select * from course inner join student_course_relation on course.course_id=student_course_relation.course_id where student_course_relation.student_id=?'
    let res = await ctx.db.EXCUTE(sql, [id])
    // console.log(res);

    ctx.body = { code: 200, msg: "查询成功", res }
})
router.post('/getEchartlist', async (ctx, next) => {//用于渲染任务列表
    let reslist, totals;
    let result = ctx.request.body;
    console.log(result);
    // let coursename = result.course;
    let workstatus = result.workstatus;
    let currentpage = result.currentpage;
    let id = result.id;
    // console.log(result);
    console.log("getWorklist");
    // console.log(coursename);

    console.log("没有课程名称");
    console.log(id);
    // let sqls = "select * from assignment where assignment_status=? order by deadline asc";
    let sqls = "select * from student_submit_assignment join assignment on assignment.assignment_id=student_submit_assignment.assignment_id where assignment.assignment_status=? and student_submit_assignment.student_id=? order by assignment.deadline asc";
    // let sqls = "select * from student_submit_assignment join assignment on assignment.assignment_id=student_submit_assignment.assignment_id where assignment.assignment_status=? and student_submit_assignment.student_id = ? order by assignment.deadline asc";
    reslist = await ctx.db.EXCUTE(sqls, ["published", id]);
    console.log(workstatus);;
    console.log(reslist.length);
    totals = reslist.length

    ctx.body = { code: 200, msg: "查询成功", reslist: reslist.slice((currentpage - 1) * 6, currentpage * 6), total: totals }
})

// 这个就是提交作业里面的获取作业列表的信息，那么一开始拿到的作业肯定的所有课程，但是是按照的时间的，需要返回的一个是否截止
router.post("/getAssignmentList", async (ctx, next) => {
    let data = ctx.request.body;
    let total;
    let inforList;
    let student_id = data.student_id;
    let submit_status = data.submit_status;
    let correction_status = data.correction_status;
    if(data.submit_status === 'unaccomplish') {
        submit_status = 'unpublish'
    }
    console.log(data);
    if (data.course_id) {
        let sql = "select assignment.assignment_title, assignment.assignment_id, assignment.publish_time, assignment.deadline, assignment.total_points, assignment.course_id, sa.student_assignment_id, course.course_name, grade.grade_name from student_submit_assignment as sa join assignment on sa.assignment_id = assignment.assignment_id join course on assignment.course_id = course.course_id join grade on course.grade_id = grade.grade_id where sa.student_id = ? and sa.submit_status = ? and sa.correction_status = ? and sa.course_id = ? order by assignment.deadline";
        let res = await ctx.db.EXCUTE(sql, [student_id, submit_status, correction_status, data.course_id]);
        inforList = res;
        if (data.submit_status === "unpublish") {
            res = res.filter(item => {
                if (new Date(item.deadline).getTime() > Date.now() && new Date(item.publish_time) < Date.now()) {
                    return item;
                }
            })
        }
        inforList = res.slice(data.pageSize * (data.pageNum - 1), data.pageNum * data.pageSize)
        total = res.length;
        console.log(res);
        ctx.body = { code: 200, list: inforList, total };
    } else {
        let sql = "select sa.student_assignment_id, assignment.assignment_title, assignment.assignment_id, assignment.course_id, assignment.publish_time, assignment.deadline, assignment.total_points, course.course_name, grade.grade_name from student_submit_assignment as sa join assignment on sa.assignment_id = assignment.assignment_id join course on assignment.course_id = course.course_id join grade on course.grade_id = grade.grade_id where sa.student_id = ? and sa.submit_status = ? and sa.correction_status = ? order by assignment.deadline";
        let res = await ctx.db.EXCUTE(sql, [student_id, submit_status, correction_status]);
        console.log(res);
        // 如果没有提交的，那么判断现在的还有多少时间截止
        if (data.submit_status === "unpublish") {
            res = res.filter(item => {
                console.log(new Date(item.deadline).getTime() > Date.now() && new Date(item.publish_time).getTime() < Date.now());
                console.log(new Date(item.deadline).getTime(), Date.now());
                if (new Date(item.deadline).getTime() > Date.now() && new Date(item.publish_time).getTime() < Date.now()) {
                    return item;
                }
            })
        } else if(data.submit_status === 'unaccomplish') {
            res = res.filter(item => {
                if(new Date(item.deadline).getTime() < Date.now()) {
                    return item
                }
            })
        }
        total = res.length;
        // 添加一个属性来说明是否截止
        res.forEach(item => {
            if(new Date(item.deadline).getTime() < Date.now()) {
                item.isdeadline = true;
            } else {
                item.isdeadline = false;
            }
        })
        inforList = res.slice(data.pageSize * (data.pageNum - 1), data.pageNum * data.pageSize)
        console.log(inforList, "info让List");
        console.log(res);
        ctx.body = { code: 200, list: inforList, total };

    }
})

router.post('/getworkdetail/:workid', async (ctx, next) => {
    const workid = ctx.params.workid
    console.log(workid);
    // let sql = 'select * from assignment where assignment_id = ?';
    // let workdetail = await ctx.db.EXCUTE(sql,[workid]);
    let sql = 'select course_id from assignment where assignment_id=?';
    let res = await ctx.db.EXCUTE(sql, [workid]);
    // console.log(res);
    res = JSON.stringify(res);
    res = JSON.parse(res);
    console.log(res[0].course_id);
    let id = res[0].course_id;
    let sqls = 'select * from assignment join course on assignment.course_id=course.course_id where course.course_id=? and assignment.assignment_id =?';//连表查询
    let workdetails = await ctx.db.EXCUTE(sqls, [id, workid]);

    console.log(workdetails);
    let sqlss = 'select * from choice join essayquestion on choice.assignment_id= essayquestion.assignment_id where essayquestion.assignment_id = ?'
    let sq = "select * from choice where assignment_id=?"
    let questiondatas = await ctx.db.EXCUTE(sqlss, [workid])
    console.log(questiondatas);
    ctx.body = { code: 200, msg: "查询成功", workdetail: workdetails, questiondata: questiondatas }

})
router.post('/gettest/:testid', async (ctx, next) => {
    const testid = ctx.params.testid
    console.log(testid);

    ctx.body = { code: 200, msg: "查询成功" }

})

router.post("/getAssignmentInfo", async (ctx, next) => {
    let assignment_id = ctx.request.body.assignmentId;
    let handle = ctx.request.body.handle;
    let assignmentInfo;
    let student_assignment_id = ctx.request.body.student_assignment_id;
    console.log(student_assignment_id);
    // console.log(ctx.request.body);
    
    if (handle === 'edit') {
        console.log(assignment_id);
        let sql1 = "select * from assignment where assignment_id = ?";
        let sql2 = "select choice.question_id, choice.choice_question, choice.answer as correct_answer, choice.question_index, choice.isMutiple, choice.proportion, choice.options_list, choice.question_type, choice.proportion, student_submit_radio.answer as student_answer from student_submit_radio join choice on student_submit_radio.question_id = choice.question_id where student_submit_radio.student_assignment_id = ?";
        let sql3 = "select essayquestion.question_id, essayquestion.essayQuestion, essayquestion.answer as correct_answer, essayquestion.question_index, essayquestion.proportion, essayquestion.question_type, essayquestion.proportion, student_submit_essay.answer as student_answer from student_submit_essay join essayquestion on student_submit_essay.question_id = essayquestion.question_id where student_submit_essay.student_assignment_id = ?";
        let res1 = await ctx.db.EXCUTE(sql1, [assignment_id]);
        let res2 = await ctx.db.EXCUTE(sql2, [student_assignment_id]);
        console.log(res2);
        let res3 = await ctx.db.EXCUTE(sql3, [student_assignment_id]);
        assignmentInfo = res1[0];
        let singleChoiceQuestions = res2.filter(item => {
            if (item.question_type === '单选题') {
                return item;
            }
        })
        let multipleChoiceQuestions = res2.filter(item => {
            if (item.question_type === '多选题') {
                return item;
            }
        })
        let shortAnswerQuestions = res3;

        singleChoiceQuestions.sort((a, b) => a.question_index - b.question_index);
        multipleChoiceQuestions.sort((a, b) => a.question_index - b.question_index);
        shortAnswerQuestions.sort((a, b) => a.question_index - b.question_index);
        let questions = {};
        questions.singleChoiceQuestions = singleChoiceQuestions;
        questions.shortAnswerQuestions = shortAnswerQuestions;
        questions.multipleChoiceQuestions = multipleChoiceQuestions;
        assignmentInfo.questions = questions;
        console.log(questions.singleChoiceQuestions, "asdasd");

        assignmentInfo.publish_time = ctx.formTime.formatDate(assignmentInfo.publish_time);
        console.log(assignmentInfo.questions, "information")
    } else {
        let sql1 = "select * from assignment where assignment_id = ?";
        let sql2 = "select choice.question_id, choice.choice_question, choice.answer as correct_answer, choice.question_index, choice.isMutiple, choice.proportion, choice.options_list, choice.question_type, choice.proportion from choice where assignment_id = ?";
        let sql3 = "select essayquestion.question_id, essayquestion.essayQuestion, essayquestion.answer as correct_answer, essayquestion.question_index, essayquestion.proportion, essayquestion.question_type, essayquestion.proportion from essayquestion where assignment_id = ?";
        let res1 = await ctx.db.EXCUTE(sql1, [assignment_id]);
        let res2 = await ctx.db.EXCUTE(sql2, [assignment_id]);
        console.log(res2);
        let res3 = await ctx.db.EXCUTE(sql3, [assignment_id]);
        assignmentInfo = res1[0];

        let singleChoiceQuestions = res2.filter(item => {
            if (item.question_type === '单选题') {
                return item;
            }
        })
        let multipleChoiceQuestions = res2.filter(item => {
            if (item.question_type === '多选题') {
                return item;
            }
        })
        let shortAnswerQuestions = res3;

        console.log(singleChoiceQuestions, "单选题");

        singleChoiceQuestions.sort((a, b) => a.question_index - b.question_index);
        multipleChoiceQuestions.sort((a, b) => a.question_index - b.question_index);
        shortAnswerQuestions.sort((a, b) => a.question_index - b.question_index);
        let questions = {};
        questions.singleChoiceQuestions = singleChoiceQuestions;
        questions.shortAnswerQuestions = shortAnswerQuestions;
        questions.multipleChoiceQuestions = multipleChoiceQuestions;
        assignmentInfo.questions = questions;
        console.log(questions.singleChoiceQuestions);

        assignmentInfo.publish_time = ctx.formTime.formatDate(assignmentInfo.publish_time);
        console.log(assignmentInfo, "123456sadas")
    }

    ctx.body = { code: 200, assignmentInfo };
})

// 学生提交作业 ，需要让学生在提交的时候自动批改选择题， 提交作业的时候让提交作业数量加1
router.post("/submitJob", async (ctx, next) => {
    let data = ctx.request.body;
    console.log(data, "data");
    let sql2 = "select student_assignment_id from student_submit_assignment where assignment_id = ? and student_id = ?"
    let res = await ctx.db.EXCUTE(sql2, [data.assignmentId, data.student_id]);
    if (data.handle === 'edit') {
        let sql = "update student_submit_assignment set update_time = ? where student_assignment_id = ?"
        await ctx.db.EXCUTE(sql, [ctx.formTime.formatDate(new Date()), res[0].student_assignment_id]);
        let radioArr = [];
        let essayArr = [];
        let updateRadioSql = "update student_submit_radio set answer = case question_id ";
        let updateEssaySql = "update student_submit_essay set answer = case question_id "
        if (data.singleArr) {
            data.singleArr.forEach(item => {
                console.log(item.answer);
                let sql = `when '${item.question_id}' then '${JSON.stringify(item.answer)}'`
                radioArr.push(sql);
            })
        }
        if (data.multipleArr) {
            data.multipleArr.forEach(item => {
                let sql = `when '${item.question_id}' then '${JSON.stringify(item.answer)}'`
                radioArr.push(sql);
            })
        }
        if (data.shortArr) {
            data.shortArr.forEach(item => {
                let sql = `when '${item.question_id}' then '${item.answer}'`;
                essayArr.push(sql);
            })
        }
        if (radioArr.length > 0) {
            let sql = updateRadioSql + radioArr.join(' ') + ' ELSE answer end';
            let res = await ctx.db.EXCUTE(sql, []);
            console.log(res);
        }
        if (essayArr.length > 0) {
            let sql = updateEssaySql + essayArr.join(' ') + ' ELSE answer end';
            let res = await ctx.db.EXCUTE(sql, []);
            console.log(res);
        }
        await autoCorrect(ctx);
        ctx.body = { code: 200 };
    } else {
        let sql = "update student_submit_assignment set submit_status = ? , submit_time = ? where assignment_id = ? and student_id = ?";
        let sql1 = "replace into student_submit_radio (question_id, question_type, answer, student_assignment_id) values "
        let sql3 = "replace into student_submit_essay (question_id, question_type, answer, student_assignment_id) values "
        let sql4 = "select publish_number from assignment where assignment_id = ?"
        let res4 = await ctx.db.EXCUTE(sql4, [data.assignmentId]);
        let publish_number = res4[0].publish_number;
        let sql5 = 'update assignment set publish_number = ? where assignment_id = ?'
        let res5 = await ctx.db.EXCUTE(sql5, [publish_number + 1, data.assignmentId]);
        let radioArr = [];
        let essayArr = [];
        let updateRes = await ctx.db.EXCUTE(sql, ["published", data.submit_time, data.assignmentId, data.student_id]);
        console.log(updateRes);
        if (data.singleArr) {
            data.singleArr.forEach(item => {
                let sql = `('${item.question_id}', '${item.question_type}', '${JSON.stringify(item.answer)}', ${res[0].student_assignment_id})`
                radioArr.push(sql);
            })
        }
        if (data.multipleArr) {
            data.multipleArr.forEach(item => {
                let sql = `('${item.question_id}', '${item.question_type}', '${JSON.stringify(item.answer)}', ${res[0].student_assignment_id})`
                radioArr.push(sql);
            })
        }
        if (data.shortArr) {
            data.shortArr.forEach(item => {
                let sql = `('${item.question_id}', '${item.question_type}', '${item.answer}', ${res[0].student_assignment_id})`
                essayArr.push(sql);
            })
        }
        if (essayArr.length > 0) {
            sql3 += essayArr.join(', ');
            let res = await ctx.db.EXCUTE(sql3, []);
            console.log(res);
        }
        if (radioArr.length > 0) {
            console.log(radioArr, "das");
            sql1 += radioArr.join(', ');
            console.log(sql1, "123456789");
            let res = await ctx.db.EXCUTE(sql1, []);
            console.log(res);
        }
        console.log(data, "这个是data");
        let list = [...data.singleArr, ...data.multipleArr];
        await autoCorrect(ctx);
        ctx.body = { code: 200 };
    }
})

// 自动批改选择题, 如果是单选题，那么就是满分，那么如果是多选题的全对给满分，不完整的没分
async function autoCorrect(ctx) {
    let data = ctx.request.body;
    console.log(data, "dwhiasohdoi");
    let sql = "select sr.question_type, sr.answer as student_answer, sr.question_id, choice.answer as correct_answer, sa.student_id, choice.proportion from student_submit_assignment as sa join student_submit_radio as sr on sa.student_assignment_id = sr.student_assignment_id join choice on sr.question_id = choice.question_id where sa.student_assignment_id = ?"

    // 需要同时更新多个表中的分数

    // 构建更新语句的数组
    let updateStatements = [];

    let res = await ctx.db.EXCUTE(sql, [data.student_assignment_id]);

    console.log(res, "res");

    let updateSql = "update student_submit_radio set score = case question_id "

    res.forEach(element => {
        // 如果题目是单选题
        if (element.question_type == "单选题") {
            let student_answer = JSON.parse(element.student_answer);
            let correct_answer = JSON.parse(element.correct_answer);
            if (correct_answer == student_answer) {
                // 如果答案是正确的，那么就让其更新分数为满分
                let score = element.proportion;
                let updateStatement = `when ${element.question_id} then ${score}`;
                updateStatements.push(updateStatement);
            } else {
                let updateStatement = `when ${element.question_id} then 0`;
                updateStatements.push(updateStatement);
            }
        }
        // 如果是多选题，那么如果选项的被正确答案包含，那么按照答对的选项占正确选项的比例来给分，如果说选项中存在不是正确选项的，那么为0分
        else if (element.question_type == "多选题") {
            let student_answer = JSON.parse(element.student_answer);
            let correct_answer = JSON.parse(element.correct_answer);
            // 检查学生的选项是否全部包含在正确答案中
            // 那么如果学生答案为空，那么直接就是错误
            let isCorrect;
            if (student_answer) {
                isCorrect = student_answer.every(option => correct_answer.includes(option));
            } else {
                isCorrect = false;
            }
            if (isCorrect) {
                console.log('该题回答正确');
                // 计算学生选择的选项占正确选项的比例，并乘以题目分值
                let proportion = student_answer.length / correct_answer.length;
                let score = Math.floor(proportion * element.proportion);
                // 构建更新语句并添加到数组中
                let updateStatement = `when ${element.question_id} then ${score}`;
                updateStatements.push(updateStatement);
            } else {
                console.log('该题回答错误');
                // 构建更新语句并添加到数组中
                let updateStatement = `when ${element.question_id} then 0`;
                updateStatements.push(updateStatement);
            }
        }
    });

    let updateQuery = updateSql + updateStatements.join(' ') + " ELSE score end";
    let resluts = await ctx.db.EXCUTE(updateQuery, [])

    ctx.body = { code: 200 };
}

// 获取作业描述
router.post("/getAssignmentDesc", async (ctx, next) => {
    console.log(ctx.request.body);
    let assignment_id = ctx.request.body.assignment_id;
    let course_id = ctx.request.body.course_id;
    console.log(course_id, "course_id");
    // console.log(id);
    console.log(assignment_id);
    let sql = 'select assignment.assignment_title, assignment.publish_time, assignment.deadline, assignment.total_points, assignment.publish_number, assignment.assignment_id, assignment.assignment_describe, teacher.teacher_name, course.course_name from assignment join teacher on assignment.teacher_id = teacher.teacher_id join course on assignment.course_id = course.course_id where assignment_id = ?';
    let sql2 = "select count(*) as totalNumber from student_course_relation where course_id = ?"
    let res = await ctx.db.EXCUTE(sql, [assignment_id]);
    let res2 = await ctx.db.EXCUTE(sql2, [course_id]);
    console.log(res);
    console.log(res2);
    let obj = res[0];
    obj.totalNumber = res2[0].totalNumber;

    ctx.body = { code: 200, data: obj }
})

module.exports = router